<template>
    <div class='imageViewItem'>
        <div class='titles'>
            {{label}}
        </div>
         <el-carousel style="height:300px;width:300px;">
            <el-carousel-item  v-for="(image,index) in imageList" :key="index">
                 <el-image
                    style="width: 100%; height: 300px"
                    :src="image.url"
                    fit="contain" 
                    :preview-src-list="srcList"  ></el-image>
            </el-carousel-item>
        </el-carousel>
        <div style='width:90%;text-align:center'>
            <el-upload
                class="upload-demo"
                drag
                ref="upload"
                action="/business/api/file/fileUpload"
                :on-success="uploadSuccess"
                
                
                 :before-upload="beforeUpload" 
                multiple>
                <el-button size="small" type="primary" >点击上传</el-button>
            </el-upload>
           
        </div>
        
    </div>
</template>
<script>
import HighShotImg from '../highShot/HighShotImg.vue'
import * as imageConversion from 'image-conversion';
export default {
    name:'imageViewMobile',
    props:['images','heights','id','data','index','isreadonly',"appid","label",'extype','exkey'],
    components:{
        HighShotImg
    },
    data(){
        return{
            srcList:[],
            dialogVisible:false,
            dialogVisible2:false,
            showType:"main",
            action:'',
            imageList:this.images,
            currentValue:'',
            styles:"",
            p:"",
            id_:""
        }
    },
    created(){
        this.srcList=[];
        if(this.images){
            for(let i=0;i<this.images.length;i++){
                this.srcList.push(this.images[i].url)
            }
        }
        

        this.setData();
        let height=this.$parent.$parent.$parent.$parent.$parent.$el.clientHeight;
        let width=this.$parent.$parent.$parent.$parent.$parent.$el.clientWidth;
        this.styles="height:"+(height-200)+"px;width:"+width+"px;";
    },
    mounted(){
        let els=document.getElementsByClassName("el-upload-dragger");
        for(let i=0;i<els.length;i++){
            els[i].style.height="40px";
        }
    },
    methods:{
        idCard(file){
            let sef=this;
            sef.getBase64(file).then(res => {
                sef.$post("api","api/baiduApi/idCard",{
                    img:res
                }).then(data=>{
                      let words_result=data.words_result;
                      let name=words_result["姓名"]["words"];  
                      let sex=words_result["性别"]["words"];  
                      let nation=words_result["民族"]["words"];  
                      let card=words_result["公民身份号码"]["words"];  
                      let address=words_result["住址"]["words"];   
                      let birth=words_result["出生"]["words"];
                      if(birth){
                          birth=birth.substring(0,4)+"-"+birth.substring(4,6)+"-"+birth.substring(6);
                      }  
                      let datas={
                          name:name,
                          sex:sex,
                          nation:nation,
                          code:card,
                          address:address,
                          birth:birth
                      }
                      
                      for(let key in sef.exkey){
                          if(key=="age"){
                              let age=sef.getAge(card);
                              sef.$set(sef.data[sef.p],sef.exkey[key],age);
                          }else
                            sef.$set(sef.data[sef.p],sef.exkey[key],datas[key]);
                      }
                });
            });
        },
         getAge(identityCard){
                var len = (identityCard + "").length;
                if (len == 0) {
                    return 0;
                } else {
                    if ((len != 15) && (len != 18))//身份证号码只能为15位或18位其它不合法
                    {
                        return 0;
                    }
                }
                var strBirthday = "";
                if (len == 18)//处理18位的身份证号码从号码中得到生日和性别代码
                {
                    strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2);
                }
                if (len == 15) {
                    strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
                }
                //时间字符串里，必须是“/”
                var birthDate = new Date(strBirthday);
                var nowDateTime = new Date();
                var age = nowDateTime.getFullYear() - birthDate.getFullYear();
                //再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
                if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
                    age--;
                }
                return age;
            },
        beforeUpload (file) { 
            let sef=this;
            return new Promise((resolve, reject) => {
                let isLt2M = file.size / 1024 / 1024 < 1 // 判定图片大小是否小于4MB
                if (isLt2M) {
                    resolve(file)
                    if(sef.extype=="idcard")
                        sef.idCard(file);
                }
                imageConversion.compressAccurately(file, 200).then(res => { // console.log(res)
                    resolve(res)
                    if(sef.extype=="idcard")
                        sef.idCard(file);
                })
            })
        },
        closes(){
            this.dialogVisible2=false;
        },
        mainDevs(){
            //this.dialogVisible2=true;
           // this.showType="main";
           this.$emit("mainDevs",this.id)
        },  
        childDevs(){
            //this.dialogVisible2=true;
           // this.showType="child";
           this.$emit("childDevs",this.id)
        },
        uploads(){
            this.dialogVisible=true;
        },
        delImg(url){
            this.$confirm('确定要删除这条图片, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let index=-1
                let index2=-1
                for(let i=0;i<this.imageList.length;i++){
                    if(this.imageList[i].url==url){
                        index=i;
                    }
                }
                for(let i=0;i<this.srcList.length;i++){
                    if(this.srcList[i]==url){
                        index2=i;
                    }
                }
                this.imageList.splice(index,1);
                this.srcList.splice(index2,1);
                this.currentValue="";
                for(let i=0;i<srcList.length;i++){
                    
                    this.currentValue=this.currentValue=="" ? srcList[i]:this.currentValue+","+srcList[i];
                }
                if(this.p){
                    this.$set(this.data[this.p],this.id_,this.currentValue);
                }else{
                    this.$set(this.data,this.id_,this.currentValue);
                }
            }).catch(() => {
             
            });
            
        },
         getBase64(file) {
            return new Promise(function(resolve, reject) {
                let reader = new FileReader();
                let imgResult = "";
                reader.readAsDataURL(file);
                reader.onload = function() {
                imgResult = reader.result;
                };
                reader.onerror = function(error) {
                reject(error);
                };
                reader.onloadend = function() {
                resolve(imgResult);
                };
            });
        },
        downImg(url){
            let a = document.createElement("a");
            
            a.href ='business/api/file/downFile?path='+url.replace("/business/image/","");
            document.body.appendChild(a);
            a.click();  //下载
            URL.revokeObjectURL(a.href);    // 释放URL 对象 
            document.body.removeChild(a);   // 删除 a 标签

        },
        uploadImg(data){
            this.uploaded(JSON.parse(data));
        },
        uploadSuccess(response, file, fileList){
            this.uploaded(response);
            
            /*
            this.$emit('input',JSON.stringify(data));
            this.$emit('on-change',JSON.stringify(data));*/
            
        },
        uploaded(response){
             if(!this.imageList){
                this.imageList=[]; 
            }
            for(let i=0;i<response.length;i++){
                this.imageList.push(response[i]);
                this.srcList.push(response[i].url)
                this.currentValue=this.currentValue=="" ? response[i].url:this.currentValue+","+response[i].url;
            }
            let data={};
            data.id=this.id;
            data.val=this.currentValue;
            data.index=this.index;
            if(this.p){
                this.$set(this.data[this.p],this.id_,this.currentValue);
            }else{
                 this.$set(this.data,this.id_,this.currentValue);
            }
            this.$message({
                message: '上传成功!',
                type: 'success'
            });
        },
        setData(){
            if(!this.images){
                if(this.data){
                    let ids=this.id.split(".");
                    if(ids.length>1){
                        this.p=ids[0];
                        this.id_=ids[1];
                        if(this.index||this.index=='0'){
                            try{
                                this.currentValue=this.data[this.p][this.index][this.id_];
                            }catch(e){}
                        }else{
                            try{
                                this.currentValue=this.data[this.p][this.id_];
                            }catch(e){}
                        }
                        
                        let images=this.currentValue.split(",");
                        this.imageList=[];
                        this.srcList=[];
                        for(let i=0;i<images.length;i++){
                            if(images[i]){
                                let data={};
                                data.url=images[i];
                                this.imageList.push(data);
                                this.srcList.push(images[i]);
                            }
                            
                        }
                    }
                
                }
            }
        }
    }
}
</script>
<style>
.imageViewItem{
    border:1px solid #ddd;
    margin:20px;
    box-sizing: border-box;
    width:90%;
}
.upload-demo{
    width:100%;
    text-align:center;
}
.el-upload-list{
    height:50px;
    overflow: auto;
}
.img_item{
    padding:10px;
    border:1px solid #ddd;
    height:120px;
    width:120px;
    display:inline-block;
    border-radius: 5px;;
    margin-left:10px;
}
.titles{
    text-align:center;
    padding:5px;
    border-bottom:1px solid #ddd;
    background:#e1e9f1;
}
.el-upload-dragger{
    width:100% !important;
}
</style>